from constants.consts import USER_AGENT_GITCODE
from db import utils
from logger import logger
from sub_events.base_event import BaseEvent

LOGGER = logger.CustomLogger()

class ManualShowOwners(BaseEvent):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.event_name_zh: str = "查询codeOwner成员"
        self.event_name_en: str = "Show CodeOwners"

    def pre_execute(self) -> bool:
        return self.hook.user_agent == USER_AGENT_GITCODE

    def execute(self):
        pr_info = self.git_client.get_pr_info(self.hook.pr_number, token=self.get_admin_token())
        assignees = pr_info.get("assignees", [])
        code_owner = []
        for assignee in assignees:
            if assignee.get("code_owner"):
                code_owner.append(assignee.get("login"))

        utils.update_pr_code_owners(self.hook, code_owner)
        comment = ""
        for group in code_owner:
            user_infos = self.OCM.owner_config['userInfos']
            if group not in self.OCM.owner_config["groups"]:
                continue
            group_members = self.OCM.owner_config["groups"].get(group, [])
            if comment:
                comment += "\n"
            comment += f"修改责任田 @{group} 相关代码, 请根据修改内容联系以下人员检视后评论\"pass\"后消分:\n"
            for member in group_members:
                if not user_infos.get(member, {}).get('info', {}):
                    continue
                comment += f"{user_infos[member]['info']} @{member}\n"
            self.comment = comment
